<?php

class ImageMagick
{
    static public function resizeImage(&$fileIn, $width, $height, $q = null, $format = null)
    {/*{{{*/
        $mw = NewMagickWand();
    	MagickReadImageBlob($mw, $fileIn['data']);

        if($format && MagickGetFormat($mw) != $format)
        {
    	    MagickSetImageFormat($mw, $format);
        }
    	$fileIn['minitype'] = MagickGetImageMimeType($mw);
    	//尺寸
    	$image_width = MagickGetImageWidth($mw);
    	$image_height = MagickGetImageHeight($mw);
    	
    	if ($image_width <= $width && $image_height <= $height)
    	{
     	    //$fileIn['data'] = MagickGetImageBlob($mw);
    	    DestroyMagickWand($mw);
    		return true;
    	}

    	$new_ratio = $width / $height;
    	$ratio = $image_width / $image_height;
    	
    	$x = $y = 0;
    	if ($new_ratio < $ratio)
    	{
    		$image_new_width = $image_height * $new_ratio;
    		$image_new_height = $image_height;
    		$x = ($image_width - $image_new_width) / 2;
    	}
    	else if($new_ratio == $ratio)
    	{
    		$image_new_height =$image_width;
    		$image_new_width = $image_height;
    	}else{
    	    $image_new_height = $image_width / $new_ratio;
    		$image_new_width = $image_width;
    		$y = $image_width * 0.1;
    	}

        //echo $image_new_width, '_' ,$image_new_height,'_' , $x,'_' , $y;die;
    	MagickSetImageFormat($mw, 'png');
    	MagickCropImage($mw, $image_new_width, $image_new_height, $x, $y) ;
    	
    	if($image_new_width > $width || $image_new_height > $height)
    	{
    	    MagickScaleImage($mw, $width, $height);
    	}
    	
    	$q && MagickSetImageCompressionQuality($mw, $q);;
        MagickStripImage($mw);

    	MagickSetImageCompression($mw, MW_RLECompression);
    	//MagickDespeckleImage($mw); //降低当前图像噪点
        //MagickEnhanceImage($mw); //用数字滤波，提高嘈杂图像质量
        $fileIn['data'] = MagickGetImageBlob($mw);
    	DestroyMagickWand($mw);
    	return true;
    }/*}}}*/
  
}

$ico = new ImageMagick();
$filename = "2.gif";
$handle = fopen($filename, "r"); 
$contents = fread($handle, filesize ($filename));
$data['data'] = $contents;
$ico->resizeImage($data, 200, 200, 75, 'gif');
header('Content-type: '.$data['minitype']);
echo $data['data'];
